import React, { useMemo } from 'react'
import { StyledRoomDetailPanel, StyledWrap, UploadIcon } from './style'
import {
	Button,
	CheckBox,
	DatePicker,
	Input,
	InputNumber,
	Message,
	Select,
	Switch,
	TextArea,
	Trigger,
} from '@kedacom/react-next'
import { useBasicInfoStore } from './store'
import shallow from 'zustand/shallow'
import { useCreateContentStore } from '../../store'
import Alert from '@/components/Alert'
import { ISelectUser } from './interface'
import { useMeetingParamsStore } from '../meetingParams/store'
import LabelWrap from '../../components/LabelWrap'
import { getHourOptions, getMinuteOptions, getTimeOptions } from './translator'
import RepeatCheckModal from './RepeatCheckModal'
import { useGlobalStore } from '@/store/global'
import { fetchCheckRegularMeeting, fetchCheckTemplateName } from '@/api/create'
import dayjs, { WEEKDAY } from '@/plugins/dayjs'
import { fetchCheckMeetingName } from '@/api/manager/meetingInfoSet'
import { fetchStatus } from '@/api/global'
import SearchRoomModal from './searchRoomModal'
import CreateMember from '../../components/CreateMember'
import ImportTemplateModal from './ImportTemplateModal'
import MeetingFileModal from './MeetingFileModal'
import { setVipList, vipSort2Users } from '../../store.combine'
import { checkPermission, getUTF8ByteCount, regexEnum } from '@/utils'
import { getRule } from '../../rules'
import { t } from 'i18next'
import { checkAndUpdateExistRoomBookedOrLocked, clearCheckedMeetingRooms, lockRoomAfterCheck } from './store.room'
import { setAll2Interactive } from '../user/store.utils'
import { changeCascadeInUser } from '../user/store.combine'
import { resetBitrateType } from '../meetingParams/store.media'

export default function BasicInfo() {
	const {
		name,
		mobilePhone,
		phoneNO,
		day,
		startTime,
		hour,
		minute,
		repeat,
		superMtNum,
		meetingFormular,
		fileNumber,
		brief,
		notifyMode,
		permanentMeeting,
		preAssignedMeetingCheck,
		preAssignedMeetingNumber,
		speaker,
		manager,
		speakerList,
		managerList,
		roomData,
		isInit,
		vipList,
		_errorMsg,
		update,
		checkMeetingName,
	} = useBasicInfoStore((state) => ({ ...state }), shallow)
	const { meetingMoid, isTemplate, maxDayForAllowBookMeeting, systemDate, _container } = useCreateContentStore(
		(state) => ({
			meetingMoid: state.meetingMoid,
			isTemplate: state.isTemplate,
			maxDayForAllowBookMeeting: state.maxDayForAllowBookMeeting,
			systemDate: state.systemDate,
			_container: state._container,
		}),
		shallow
	)
	const { meetingType, simpleCascade } = useMeetingParamsStore((state) => ({
		meetingType: state.meetingType,
		simpleCascade: state.simpleCascade,
	}))
	const { user, serverInfo, SWITCH } = useGlobalStore(
		(state) => ({ user: state.user, serverInfo: state.serverInfo, SWITCH: state.SWITCH }),
		shallow
	)

	const nameLimit = useMemo(
		() =>
			SWITCH.characterLimit
				? [
						{
							regex: regexEnum.nameIllegal,
							msg: isTemplate
								? t('模板名称存在非法字符，请重新输入')
								: t('会议名称存在非法字符，请重新输入'),
						},
						{
							regex: (v: string) =>
								!/^[\u4e00-\u9fa5A-Za-z0-9]/.test(v) || !/[\u4e00-\u9fa5A-Za-z0-9]$/.test(v),
							msg: t('首尾字符仅允许输入：英文、数字、汉字'),
						},
				  ]
				: [
						{
							regex: (v: string) => {
								let len = getUTF8ByteCount(v)
								return len > 100
							},
							msg: t('输入内容超过长度限制'),
						},
				  ],
		[SWITCH.characterLimit]
	)

	const mobileLimit = useMemo(() => {
		let rule = getRule('mobilePhone')
		if (SWITCH.characterLimit) {
			;(rule.regular as any).push({
				regex: (val: string) => !(val.length === 11 || val.length === 0),
				msg: t('手机号码应为11个字符'),
			})
		}
		return rule
	}, [SWITCH.characterLimit])

	const searchRoom = () => {
		fetchStatus(() => {
			if (!!serverInfo?.stand_alone) {
				Alert(t('当前机房为独立运行状态，无法操作！'))
				return
			}
			if (repeat) {
				let m = Message.loading(t('正在检测能否生成会议，请稍候……'))
				fetchCheckRegularMeeting({
					frequency: 1,
					week_days: meetingFormular?.weekDays ?? '',
					start_date: day,
					end_date: meetingFormular?.endTime ?? '',
				}).then((res) => {
					m.hide()
					if (res.success) {
						if (!res.data) {
							Alert(t('结束时间选择有误，导致重复周期无效，请调整'))
						} else {
							update({ _isSearchRoomDialogShow: true })
						}
					} else {
						Alert(t('检测是否可生成会议出错'))
					}
				})
			} else {
				update({ _isSearchRoomDialogShow: true })
			}
		})
	}

	const getRoomDesc = () => {
		if (!roomData) return ''
		if (roomData.status === 1) {
			if (repeat) {
				return (
					<span style={{ color: '#007ac0' }}>
						{t('{{num}}次会议的会议室全部推荐成功', { num: roomData.total_num })}
					</span>
				)
			} else {
				return (
					<span style={{ color: '#007ac0' }}>
						{t('{{num}}个会议室推荐成功', { num: roomData.success_num })}
					</span>
				)
			}
		} else if (roomData.status === 2) {
			if (repeat) {
				return (
					<span style={{ color: 'red' }}>
						{t('{{num}}次会议的会议室部分推荐成功', { num: roomData.total_num })}
					</span>
				)
			} else {
				return (
					<span style={{ color: 'red' }}>{t('{{num}}个会议室推荐失败', { num: roomData.failure_num })}</span>
				)
			}
		} else {
			if (repeat) {
				return (
					<span style={{ color: 'red' }}>
						{t('{{num}}次会议的会议室全部推荐失败', { num: roomData.total_num })}
					</span>
				)
			} else {
				return (
					<span style={{ color: 'red' }}>{t('{{num}}个会议室推荐失败', { num: roomData.failure_num })}</span>
				)
			}
		}
	}

	const roomDetailPanel = (
		<StyledRoomDetailPanel>
			{roomData?.data.map((item) =>
				item.meeting_rooms.map((j, index) => (
					<div className="line" key={index}>
						<span className="day">{index === 0 ? item.day : ''}</span>
						<span>{j.region_name}</span>
						{!j.name ? <span style={{ color: 'red' }}>{t('无')}</span> : <span>{j.name}</span>}
					</div>
				))
			)}
		</StyledRoomDetailPanel>
	)

	const mobileContainer = (
		<LabelWrap label={t('联系方式')} className="mobile-wrap" show={!!SWITCH.create.contactWay}>
			<InputNumber
				width={187}
				placeholder={t('手机号码')}
				focusMsg={t('请输入11位手机号码')}
				maxLength={11}
				value={mobilePhone}
				rule={mobileLimit}
				onChange={(e, v) => {
					update({ mobilePhone: v })
				}}
				style={{ marginRight: 45 }}
			/>
			<Input
				width={135}
				placeholder={t('分机号码')}
				focusMsg={t('最多10个字符,包括数字、"."、"_"、"-"、"*"、"#"、空格')}
				maxLength={10}
				value={phoneNO}
				rule={getRule('phoneNO')}
				onChange={(e, v) => {
					update({ phoneNO: v })
				}}
			/>
		</LabelWrap>
	)

	return (
		<StyledWrap className="tpl-basic">
			<LabelWrap label={t('会议名称')}>
				<Input
					width={485}
					placeholder={isTemplate ? t('请输入模板名称') : t('请输入会议名称')}
					focusMsg={
						SWITCH.characterLimit
							? t(`最多可输入32个字符，包括英文、汉字、数字、" "、"_"、"-"、"@"、"."、"("、")"、"#"`)
							: undefined
					}
					maxLength={SWITCH.characterLimit ? 32 : undefined}
					validateMsg={_errorMsg}
					rule={{
						required: {
							msg: isTemplate ? t('模板名称不能为空') : t('会议名称不能为空'),
						},
						regular: [
							...nameLimit,
							{
								regex: async (value) => {
									let flag = false
									if (isTemplate) {
										console.log('模板名称校验')
										let res = await fetchCheckTemplateName(value, meetingMoid)
										flag = !!!res.success
									} else {
										if (repeat || isInit) return false //初始化，例会不会进行名字校验
										console.log('会议名称校验')
										let _startTime = day + ' ' + startTime + ':00'
										let _endTime = permanentMeeting
											? undefined
											: dayjs(_startTime)
													.add(hour * 60 + minute, 'minute')
													.format('YYYY-MM-DD HH:mm:ss')
										let res = await fetchCheckMeetingName({
											conf_name: value,
											end_time: dayjs(_endTime).format(),
											start_time: dayjs(_startTime).format(),
											meeting_id: meetingMoid,
										})
										flag = !res
									}
									return flag
								},
								msg: isTemplate ? t('模板名称已存在') : t('会议名称已存在'),
							},
						],
					}}
					value={name}
					onChange={(e, v) => update({ name: v })}
					onFocus={() => update({ _errorMsg: null })}
				></Input>
			</LabelWrap>
			{isTemplate && mobileContainer}
			<LabelWrap label={t('会议日期')} show={!isTemplate}>
				<DatePicker
					container={() => _container}
					style={{ marginRight: 20 }}
					inputWidth={100}
					minDate={systemDate}
					maxDate={maxDayForAllowBookMeeting}
					value={day}
					onChange={(e, dateString) => {
						let preVal = day
						update({ day: dateString })
						checkMeetingName()
						checkAndUpdateExistRoomBookedOrLocked((res) => {
							if (res.success) {
								//无冲突会议室
								if (res.data) {
									lockRoomAfterCheck()
								} else {
									clearCheckedMeetingRooms(
										() => {
											if (repeat) {
												//是否会议室并更新例会信息
												update({
													meetingFormular: {
														weekDays: dayjs(dateString).day().toString(),
														endTime: dayjs(dateString).add(7, 'day').format('YYYY-MM-DD'),
													},
												})
											}
										},
										() => {
											update({ day: preVal })
											checkMeetingName()
										},
										t('更改时间会释放您锁定和预定的所有会议室，是否继续?')
									)
								}
							}
						})
					}}
					i18n={{
						confirm: t('确认'),
						year: t('年'),
						month: [
							t('1月'),
							t('2月'),
							t('3月'),
							t('4月'),
							t('5月'),
							t('6月'),
							t('7月'),
							t('8月'),
							t('9月'),
							t('10月'),
							t('11月'),
							t('12月'),
						],
						week: [t('日'), t('一'), t('二'), t('三'), t('四'), t('五'), t('六')],
					}}
				/>
				<Select
					container={() => _container}
					width={143}
					options={getTimeOptions()}
					value={startTime}
					onChange={(e, v) => {
						let preVal = startTime
						update({ startTime: v })
						checkMeetingName()
						checkAndUpdateExistRoomBookedOrLocked((res) => {
							if (res.success) {
								if (res.data) {
									lockRoomAfterCheck()
								} else {
									clearCheckedMeetingRooms(
										() => {},
										() => {
											update({ startTime: preVal })
											checkMeetingName()
										},
										t('更改时间会释放您锁定和预定的所有会议室，是否继续?')
									)
								}
							}
						})
					}}
				/>
			</LabelWrap>
			<LabelWrap label={t('会议时长')} className="duration-wrap">
				<div className="line">
					<Select
						container={() => _container}
						className="hour"
						width={65}
						options={getHourOptions()}
						disabled={permanentMeeting}
						value={hour}
						onChange={(e, v) => {
							let preHourVal = hour
							let preMinuteVal = minute
							if (!isTemplate) {
								update({ hour: v, minute: v === 24 ? 0 : minute })
								checkMeetingName()
								checkAndUpdateExistRoomBookedOrLocked((res) => {
									if (res.success) {
										if (res.data) {
											lockRoomAfterCheck()
										} else {
											clearCheckedMeetingRooms(
												() => {},
												() => {
													update({ hour: preHourVal, minute: preMinuteVal })
													checkMeetingName()
												},
												t('更改时间会释放您锁定和预定的所有会议室，是否继续?')
											)
										}
									}
								})
							} else {
								update({ hour: v, minute: v === 24 ? 0 : minute })
							}
						}}
					/>
					<span style={{ margin: '0 20px 0 10px' }}>{t('小时')}</span>
					<Select
						container={() => _container}
						className="minute"
						width={62}
						options={getMinuteOptions(hour)}
						disabled={permanentMeeting}
						value={minute}
						onChange={(e, v) => {
							let preVal = minute
							if (!isTemplate) {
								update({ minute: v })
								checkMeetingName()
								checkAndUpdateExistRoomBookedOrLocked((res) => {
									if (res.success) {
										if (res.data) {
											lockRoomAfterCheck()
										} else {
											clearCheckedMeetingRooms(
												() => {},
												() => {
													update({ minute: preVal })
													checkMeetingName()
												},
												t('更改时间会释放您锁定和预定的所有会议室，是否继续?')
											)
										}
									}
								})
							} else {
								update({ minute: v })
							}
						}}
					/>
					<span style={{ margin: '0 40px 0 10px' }}>{t('分钟')}</span>
					<CheckBox
						disabled={repeat}
						checked={permanentMeeting}
						onChange={(e, v) => {
							if (!isTemplate) {
								clearCheckedMeetingRooms(
									() => {
										update({ permanentMeeting: v })
										checkMeetingName()
									},
									() => {},
									t('您更改了会议时间属性为永久,系统将自动释放原本锁定和预定的会议室，是否继续？')
								)
							} else {
								update({ permanentMeeting: v })
							}
						}}
					>
						{t('手动结束')}
					</CheckBox>
					{hour === 0 && minute === 0 && !permanentMeeting && (
						<div className="error-tip">{t('会议时长不能为0')}</div>
					)}
				</div>
				{!isTemplate && !meetingMoid && (
					<div className="repeat-wrap">
						<CheckBox
							disabled={permanentMeeting}
							checked={repeat}
							onChange={(e, v) => {
								if (!meetingFormular) {
									if (v) {
										update({ _isRepeatDialogShow: true })
									}
								} else {
									clearCheckedMeetingRooms(
										() => {
											update({ repeat: v })
											checkMeetingName()
										},
										() => {},
										t('更换重复类型会释放您锁定和预定的所有会议室，是否继续?')
									)
								}
							}}
						>
							{t('重复')}
						</CheckBox>
						{repeat && meetingFormular && (
							<span className="desc">
								{t('每周的{{name}}进行，直到{{date}}', {
									name: meetingFormular.weekDays
										.split(',')
										.map((val) => WEEKDAY[Number(val)])
										.join('、'),
									date: meetingFormular.endTime,
								})}

								<span
									className="modify"
									onClick={() => {
										update({ _isRepeatDialogShow: true })
									}}
								>
									{t('修改')}
								</span>
							</span>
						)}
					</div>
				)}
			</LabelWrap>
			<LabelWrap label={t('预分配会议号')} show={isTemplate} className="pre-number-wrap">
				<Switch
					width={40}
					height={22}
					checked={preAssignedMeetingCheck}
					disabled={simpleCascade === 2}
					onChange={(e, v) => {
						update({ preAssignedMeetingCheck: v })
					}}
				></Switch>
				{preAssignedMeetingNumber !== '' ? (
					<span className="tip">
						{t('系统分配：')} {preAssignedMeetingNumber}
					</span>
				) : preAssignedMeetingCheck ? (
					<span className="tip">{t('保存模板获取预分配号码')}</span>
				) : (
					<></>
				)}
			</LabelWrap>
			<LabelWrap label={t('超大方会议')} show={!!SWITCH.create.superNumMt && serverInfo?.enable_audience}>
				<Switch
					width={40}
					height={22}
					checked={superMtNum}
					onChange={(e, v) => {
						if (useMeetingParamsStore.getState().simpleCascade === 2) {
							Alert(t('超大方会议不支持智能级联'))
							return
						}
						if (
							useMeetingParamsStore.getState().meetingType === 0 &&
							useMeetingParamsStore.getState().sourceUsed === 2
						) {
							Alert(t('传统会议纯转发会议不支持超大方。'))
							return
						}
						update({ superMtNum: v })
						//超大方设置级联方式为简单级联
						useMeetingParamsStore.setState({ simpleCascade: 0 })
						resetBitrateType()
						setAll2Interactive()
						changeCascadeInUser(false)
					}}
				></Switch>
			</LabelWrap>
			<LabelWrap label={t('会议模板')} show={!isTemplate}>
				<Button
					onClick={() => {
						update({ _isImportTemplateShow: true })
					}}
				>
					{t('导入模板')}
				</Button>
			</LabelWrap>
			<LabelWrap
				label={t('会议室')}
				className="room-wrap"
				show={!isTemplate && !!(serverInfo?.enable_room && user?.enable_kis) && !!SWITCH.kis.room}
			>
				<Button onClick={searchRoom} disabled={permanentMeeting}>
					{t('查找会议室')}
				</Button>
				{roomData && (
					<span className="desc">
						<span className="warn">{getRoomDesc()}</span>
						{roomData?.status !== 3 && (
							<Trigger popup={roomDetailPanel} popupPlacement="bottomStart">
								<span className="detail">{t('会议室详情')}</span>
							</Trigger>
						)}
					</span>
				)}
			</LabelWrap>
			{!isTemplate && mobileContainer}
			<LabelWrap
				label={t('文件管理', { context: 'SC1' })}
				show={!isTemplate && !!user?.enable_upload && SWITCH.fileManager}
				className="file-wrap"
			>
				<span>{t('已上传{{num}}个文档', { num: fileNumber })} </span>
				<UploadIcon onClick={() => update({ _isMeetingFileShow: true })}></UploadIcon>
			</LabelWrap>
			<LabelWrap label={t('会议概要')} show={!isTemplate} className="brief-wrap">
				<TextArea
					width={450}
					value={brief}
					rows={4}
					onChange={(e, v) => {
						update({ brief: v })
					}}
				/>
				<span className={`tip ${brief.length > 500 ? 'error' : ''} `}>{t('最多可输入500个字')}</span>
			</LabelWrap>
			<LabelWrap label={t('通知方式')} show={!isTemplate}>
				{checkPermission('100', SWITCH.create.notifyMode) && (
					<CheckBox
						width={120}
						checked={notifyMode.email}
						onChange={(e, v) => {
							update({ notifyMode: { ...notifyMode, email: v } })
						}}
					>
						{t('邮件通知')}
					</CheckBox>
				)}
				{checkPermission('010', SWITCH.create.notifyMode) && !!user?.enable_meeting_sms && (
					<CheckBox
						width={120}
						checked={notifyMode.sms}
						onChange={(e, v) => {
							update({ notifyMode: { ...notifyMode, sms: v } })
						}}
					>
						{t('短信通知')}
					</CheckBox>
				)}
				{checkPermission('001', SWITCH.create.notifyMode) && !!user?.enable_meeting_wechat && (
					<CheckBox
						width={120}
						checked={notifyMode.wechat}
						onChange={(e, v) => {
							update({ notifyMode: { ...notifyMode, wechat: v } })
						}}
					>
						{t('微信通知')}
					</CheckBox>
				)}
			</LabelWrap>
			<LabelWrap label={t('发言方')}>
				<Select
					container={() => _container}
					width={187}
					canSearch={true}
					options={speakerList}
					value={speaker.uid}
					valueField="uid"
					labelField="name"
					onChange={(e, v, obj) => {
						if (useMeetingParamsStore.getState().voiceInspireEnable) {
							//开启语音激励不允许设置发言方
							Alert(t('语音激励功能已开启，不可手动设置发言人。终端发言可自动激励成为发言人。(20346)'))
						} else {
							update({ speaker: obj as ISelectUser })
						}
					}}
				/>
			</LabelWrap>
			<LabelWrap label={t('管理方')}>
				<Select
					container={() => _container}
					width={187}
					canSearch={true}
					options={managerList}
					value={manager.uid}
					valueField="uid"
					labelField="name"
					onChange={(e, v, obj) => {
						update({ manager: obj as ISelectUser })
					}}
				/>
			</LabelWrap>
			<LabelWrap label={t('VIP设置')} show={meetingType !== 2} className="vip-wrap">
				<CreateMember
					list={vipList}
					setOuterList={(h, type) => {
						if (type === 'drop') {
							setVipList(h)
						} else {
							update({ vipList: h })
						}
						vipSort2Users()
					}}
				></CreateMember>
			</LabelWrap>
			<RepeatCheckModal />
			<SearchRoomModal />
			<ImportTemplateModal />
			<MeetingFileModal />
		</StyledWrap>
	)
}
